﻿using System;
using System.Windows;
using SmsReceiverApp.Services;
using SmsReceiverApp.Views;
using SmsReceiverApp.Extensions;

namespace SmsReceiverApp;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private TrayIconManager? _trayIconManager;
    private NetworkListenerService? _networkService;
    private CodeExtractionService? _codeService;
    private SettingsManager? _settingsManager;
    private MessageHistoryService? _messageHistoryService;
    private LoggingService? _logger;
    private MainWindow? _mainWindow;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        // 设置控制台编码为UTF-8，解决中文乱码问题
        try
        {
            System.Console.OutputEncoding = System.Text.Encoding.UTF8;
            System.Console.InputEncoding = System.Text.Encoding.UTF8;
        }
        catch
        {
            // 忽略编码设置错误
        }

        // 初始化本地化服务
        InitializeLocalization();

        // 在调试模式下运行语言检测测试
        #if DEBUG
        RunLanguageDetectionTest();
        #endif

        // 初始化服务
        InitializeServices();

        // 设置应用不显示主窗口，只显示托盘图标
        MainWindow = null;
        ShutdownMode = ShutdownMode.OnExplicitShutdown;
    }

    private void InitializeServices()
    {
        try
        {
            // 初始化设置管理器（需要先初始化以获取日志设置）
            _settingsManager = new SettingsManager();

            // 根据设置初始化日志服务
            _logger = new LoggingService(LogLevel.Debug, enableConsoleOutput: true, enableFileOutput: _settingsManager.Settings.EnableLogFile);
            _logger.LogInfo("=== SMS Receiver Application Starting ===");
            _logger.LogInfo($"Application version: 1.0.0");
            _logger.LogInfo($"OS: {Environment.OSVersion}");
            _logger.LogInfo($".NET Version: {Environment.Version}");
            _logger.LogInfo($"Log file enabled: {_settingsManager.Settings.EnableLogFile}");

            // 只有在启用文件日志时才清理旧日志文件
            if (_settingsManager.Settings.EnableLogFile)
            {
                _logger.CleanupOldLogs(7);
            }

            _logger.LogInfo("Settings manager initialized");

            // 初始化消息历史服务（最多存储10封邮件）
            _messageHistoryService = new MessageHistoryService(10, _logger);
            _logger.LogInfo("Message history service initialized with persistent storage");

            // 初始化验证码提取服务
            _codeService = new CodeExtractionService(_settingsManager.Settings);
            _logger.LogInfo("Code extraction service initialized");

            // 初始化网络监听服务
            _networkService = new NetworkListenerService(_logger);
            _networkService.MessageReceived += OnMessageReceived;
            _networkService.ErrorOccurred += OnNetworkError;
            _logger.LogInfo("Network listener service initialized");

            // 初始化托盘图标管理器
            _trayIconManager = new TrayIconManager();
            _trayIconManager.ShowMainWindowRequested += OnShowMainWindowRequested;
            _trayIconManager.ShowSettingsRequested += OnShowSettingsRequested;
            _trayIconManager.ShowRecentMessagesRequested += OnShowRecentMessagesRequested;
            _trayIconManager.ExitApplicationRequested += OnExitApplicationRequested;
            _trayIconManager.Initialize();
            _logger.LogInfo("Tray icon manager initialized");

            // 如果设置启用，开始监听
            if (_settingsManager.Settings.IsEnabled)
            {
                StartNetworkService();
            }
            else
            {
                _logger.LogInfo("Network service disabled in settings");
            }

            // 监听设置变化
            _settingsManager.SettingsChanged += OnSettingsChanged;

            _logger.LogInfo("All services initialized successfully");
        }
        catch (Exception ex)
        {
            _logger?.LogError($"Application initialization failed: {ex.Message}", ex);
            MessageBox.Show($"Application initialization failed: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            Shutdown();
        }
    }

    private async void StartNetworkService()
    {
        try
        {
            if (_networkService != null && _settingsManager != null)
            {
                var port = _settingsManager.Settings.ListenPort;
                _logger?.LogInfo($"Starting network service on port {port}");

                await _networkService.StartAsync(port);
                _trayIconManager?.SetIconState(true);

                _logger?.LogInfo($"Network service started successfully on port {port}");
                _trayIconManager?.ShowBalloonTip("SMS Receiver", $"Service started on port {port}", Hardcodet.Wpf.TaskbarNotification.BalloonIcon.Info);
            }
        }
        catch (Exception ex)
        {
            _logger?.LogError($"Failed to start network service: {ex.Message}", ex);
            MessageBox.Show($"Failed to start network service: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private async void StopNetworkService()
    {
        try
        {
            if (_networkService != null)
            {
                _logger?.LogInfo("Stopping network service");
                await _networkService.StopAsync();
                _trayIconManager?.SetIconState(false);
                _logger?.LogInfo("Network service stopped successfully");
            }
        }
        catch (Exception ex)
        {
            _logger?.LogError($"Failed to stop network service: {ex.Message}", ex);
        }
    }

    private void OnMessageReceived(object? sender, Models.SmsMessage message)
    {
        try
        {
            _logger?.LogInfo($"Message received: From={message.Sender}, Length={message.Content.Length}, IP={message.ClientIP}");

            // 处理验证码提取
            _codeService?.ProcessMessage(message);

            // 如果包含验证码且启用了自动复制，自动复制到剪贴板
            if (message.ContainsVerificationCode &&
                !string.IsNullOrEmpty(message.ExtractedCode) &&
                _settingsManager?.Settings.AutoCopyCode == true)
            {
                try
                {
                    var copySuccess = _codeService?.CopyToClipboard(message.ExtractedCode) ?? false;
                    if (copySuccess)
                    {
                        _logger?.LogInfo($"Verification code auto-copied to clipboard: {message.ExtractedCode}");
                    }
                    else
                    {
                        _logger?.LogWarning($"Failed to auto-copy verification code: {message.ExtractedCode}");
                    }
                }
                catch (Exception copyEx)
                {
                    _logger?.LogError($"Error auto-copying verification code: {copyEx.Message}", copyEx);
                }
            }

            // 添加到历史记录
            _messageHistoryService?.AddMessage(message);

            // 显示通知
            if (_settingsManager?.Settings.ShowAllMessages == true || message.ContainsVerificationCode)
            {
                _logger?.LogDebug($"Showing notification for message: HasCode={message.ContainsVerificationCode}");

                Dispatcher.Invoke(() =>
                {
                    var notificationWindow = new NotificationWindow(message, _settingsManager.Settings, _codeService!);
                    notificationWindow.Show();
                });
            }
            else
            {
                _logger?.LogDebug("Message notification skipped (not showing all messages and no verification code)");
            }
        }
        catch (Exception ex)
        {
            _logger?.LogError($"Error processing received message: {ex.Message}", ex);
        }
    }

    private void OnNetworkError(object? sender, string error)
    {
        _logger?.LogError($"Network error: {error}");
        _trayIconManager?.ShowBalloonTip("Tray_NetworkError".GetLocalizedString(), error, Hardcodet.Wpf.TaskbarNotification.BalloonIcon.Error);
    }

    private void OnShowMainWindowRequested(object? sender, EventArgs e)
    {
        _logger?.LogInfo("Show main window requested");
        ShowMainTabWindow(0); // 显示消息Tab作为主窗口
    }

    private void OnShowSettingsRequested(object? sender, EventArgs e)
    {
        _logger?.LogInfo("Show settings requested");
        ShowMainTabWindow(1); // 显示设置Tab
    }

    private void OnShowRecentMessagesRequested(object? sender, EventArgs e)
    {
        _logger?.LogInfo("Show recent messages requested");
        ShowMainTabWindow(0); // 显示消息Tab
    }

    private void OnExitApplicationRequested(object? sender, EventArgs e)
    {
        _logger?.LogInfo("Exit application requested");
        ExitApplication();
    }

    private void OnSettingsChanged(object? sender, Models.AppSettings settings)
    {
        // 检查日志文件设置是否变化，如果变化则重新初始化日志服务
        var currentLogFileEnabled = _logger != null && _logger.LogFileExists();
        if (currentLogFileEnabled != settings.EnableLogFile)
        {
            _logger?.LogInfo($"Log file setting changed to: {settings.EnableLogFile}");

            // 重新初始化日志服务
            _logger = new LoggingService(LogLevel.Debug, enableConsoleOutput: true, enableFileOutput: settings.EnableLogFile);
            _logger.LogInfo("Log service reinitialized due to settings change");

            // 更新其他服务的日志引用
            if (_messageHistoryService != null)
            {
                // MessageHistoryService 使用自己的日志实例，这里不需要更新
            }
        }

        // 重新创建验证码服务
        _codeService = new CodeExtractionService(settings);

        // 重启网络服务
        if (settings.IsEnabled && _networkService?.IsRunning != true)
        {
            StartNetworkService();
        }
        else if (!settings.IsEnabled && _networkService?.IsRunning == true)
        {
            StopNetworkService();
        }
        else if (settings.IsEnabled && _networkService?.IsRunning == true && _networkService.Port != settings.ListenPort)
        {
            // 端口变化，重启服务
            StopNetworkService();
            StartNetworkService();
        }
    }



    private Views.MainTabWindow? _mainTabWindow;

    private void ShowMainTabWindow(int selectedTabIndex = 0)
    {
        try
        {
            if (_messageHistoryService != null && _codeService != null && _logger != null && _settingsManager != null)
            {
                _logger.LogInfo($"Opening main tab window (tab: {selectedTabIndex})");

                // 如果窗口已存在，激活并切换到指定Tab
                if (_mainTabWindow != null)
                {
                    if (_mainTabWindow.WindowState == WindowState.Minimized)
                    {
                        _mainTabWindow.WindowState = WindowState.Normal;
                    }
                    _mainTabWindow.Show();
                    _mainTabWindow.Activate();

                    // 切换到指定的Tab
                    _mainTabWindow.TabControl.SelectedIndex = selectedTabIndex;
                }
                else
                {
                    // 创建新窗口
                    _mainTabWindow = new Views.MainTabWindow(_messageHistoryService, _codeService, _logger, _settingsManager);
                    _mainTabWindow.Closed += (s, e) => _mainTabWindow = null;
                    _mainTabWindow.TabControl.SelectedIndex = selectedTabIndex;
                    _mainTabWindow.Show();
                }
            }
            else
            {
                _logger?.LogWarning("Cannot show main tab window - required services not initialized");
                MessageBox.Show("Required services are not available.", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        catch (Exception ex)
        {
            _logger?.LogError($"Error showing main tab window: {ex.Message}", ex);
            MessageBox.Show($"Error opening main window: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private async void ExitApplication()
    {
        try
        {
            _logger?.LogInfo("=== SMS Receiver Application Shutting Down ===");

            // 停止网络服务
            StopNetworkService();

            // 释放托盘图标
            _trayIconManager?.Dispose();

            _logger?.LogInfo("Application shutdown completed");

            // 关闭应用
            Shutdown();
        }
        catch (Exception ex)
        {
            _logger?.LogError($"Error during application shutdown: {ex.Message}", ex);
            Shutdown();
        }
    }

    /// <summary>
    /// 初始化本地化服务
    /// </summary>
    private void InitializeLocalization()
    {
        try
        {
            var settingsManager = new SettingsManager();
            var savedLanguage = settingsManager.Settings.Language;

            // 检查是否是首次启动（语言设置为默认值或null）
            // 注意：当settings.json存在但不包含Language属性时，savedLanguage会是null而不是空字符串
            bool isFirstRun = string.IsNullOrEmpty(savedLanguage);

            if (isFirstRun)
            {
                // 首次启动：使用LocalizationService的智能语言检测
                var detectedLanguage = LocalizationService.Instance.CurrentCulture.Name;

                // 显示语言选择窗口让用户确认
                var selectedLanguage = ShowLanguageSelectionDialog(detectedLanguage);

                // 保存用户选择的语言到设置
                settingsManager.Settings.Language = selectedLanguage;
                settingsManager.SaveSettings();

                // 应用选择的语言
                if (selectedLanguage != detectedLanguage)
                {
                    LocalizationService.Instance.SetLanguage(selectedLanguage);
                }

                // 记录语言选择信息
                var selectionInfo = LocalizationService.Instance.GetLanguageSelectionInfo();
                System.Diagnostics.Debug.WriteLine($"First run language selection:\n{selectionInfo}");

                // 如果有日志服务，记录语言选择
                try
                {
                    var logger = new LoggingService();
                    logger.LogInfo($"First run: User selected language '{selectedLanguage}' ({LocalizationService.GetLanguageDisplayName(selectedLanguage)})");
                    logger.LogDebug($"Language selection details:\n{selectionInfo}");
                }
                catch
                {
                    // 忽略日志记录错误
                }
            }
            else
            {
                // 非首次启动：使用保存的语言设置
                if (LocalizationService.IsLanguageSupported(savedLanguage))
                {
                    LocalizationService.Instance.SetLanguage(savedLanguage);
                }
                else
                {
                    // 如果保存的语言不再支持，重新检测
                    var detectedLanguage = LocalizationService.Instance.CurrentCulture.Name;
                    settingsManager.Settings.Language = detectedLanguage;
                    settingsManager.SaveSettings();

                    try
                    {
                        var logger = new LoggingService();
                        logger.LogWarning($"Saved language '{savedLanguage}' not supported, switched to '{detectedLanguage}'");
                    }
                    catch
                    {
                        // 忽略日志记录错误
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // 如果初始化失败，使用英语作为默认语言
            System.Diagnostics.Debug.WriteLine($"Failed to initialize localization: {ex.Message}");
            try
            {
                LocalizationService.Instance.SetLanguage("en-US");
                var settingsManager = new SettingsManager();
                settingsManager.Settings.Language = "en-US";
                settingsManager.SaveSettings();
            }
            catch
            {
                // 忽略保存错误
            }
        }
    }

    /// <summary>
    /// 显示语言选择对话框
    /// </summary>
    /// <param name="detectedLanguage">检测到的语言</param>
    /// <returns>用户选择的语言代码</returns>
    private string ShowLanguageSelectionDialog(string detectedLanguage)
    {
        try
        {
            var languageWindow = new Views.LanguageSelectionWindow(detectedLanguage);

            // 显示为模态对话框
            var result = languageWindow.ShowDialog();

            if (result == true && !string.IsNullOrEmpty(languageWindow.SelectedLanguage))
            {
                return languageWindow.SelectedLanguage;
            }
            else
            {
                // 用户取消或关闭窗口，使用检测到的语言
                return detectedLanguage;
            }
        }
        catch (Exception ex)
        {
            // 如果显示对话框失败，使用检测到的语言
            System.Diagnostics.Debug.WriteLine($"Failed to show language selection dialog: {ex.Message}");
            return detectedLanguage;
        }
    }

    /// <summary>
    /// 运行语言检测测试（仅在调试模式下）
    /// </summary>
    private void RunLanguageDetectionTest()
    {
        try
        {
            System.Diagnostics.Debug.WriteLine("=== Language Detection Test ===");

            var localizationService = LocalizationService.Instance;
            var detectedLanguage = localizationService.CurrentCulture.Name;
            var displayName = LocalizationService.GetLanguageDisplayName(detectedLanguage);

            System.Diagnostics.Debug.WriteLine($"Detected Language: {detectedLanguage} ({displayName})");

            var selectionInfo = localizationService.GetLanguageSelectionInfo();
            System.Diagnostics.Debug.WriteLine($"Selection Details:\n{selectionInfo}");

            // 测试几个关键的本地化字符串
            var testKeys = new[] { "MainWindow_Title", "Settings_Language", "Button_Save", "Tray_Running" };
            foreach (var key in testKeys)
            {
                var localizedText = key.GetLocalizedString($"[{key}]");
                System.Diagnostics.Debug.WriteLine($"  {key}: {localizedText}");
            }

            System.Diagnostics.Debug.WriteLine("=== End Language Detection Test ===");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Language detection test failed: {ex.Message}");
        }
    }

    protected override void OnExit(ExitEventArgs e)
    {
        _trayIconManager?.Dispose();
        _networkService?.Dispose();
        base.OnExit(e);
    }
}